package com.sky.WebSocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/ws/{cid}")
@Slf4j
public class WebSocketServer {
    private static final Map<String, Session> map = new HashMap<>();

    /**
     * 连接成功回调的方法
     *
     * @param session
     * @param cid
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("cid") String cid) {
        log.info("客户端 {} 建立连接", cid);
        log.info("session => {}", session);
        map.put(cid, session);
    }

    @OnMessage
    public void onMessage(String msg, @PathParam("cid") String cid) {
        log.info("收到客户端 {} 消息 {}", cid, msg);
    }

    @OnClose
    public void onClose(@PathParam("cid") String cid) {
        log.info("连接关闭 {}", cid);
        map.remove(cid);
    }

    /**
     * 群发消息
     *
     * @param text
     */
    public void sendAllSession(String text) {
        Collection<Session> sessions = map.values();
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(text);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
